package com.foo.DeCompressData;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.ejb.Stateless;

/**
 * Session Bean implementation class UnArchive
 */
@Stateless
public class DeCompress implements DeCompressRemote, DeCompressLocal {

	public int BUFFER_SIZE = 4096;
    /**
     * Default constructor. 
     */
    public DeCompress() {
        
    }

	@Override
	public boolean unzipFile(String archiveFileName) {
		try
		{
		 BufferedOutputStream dest = null;
	     FileInputStream fis = new FileInputStream(new File(archiveFileName).getAbsolutePath());
	     ZipInputStream zis = new  ZipInputStream(new BufferedInputStream(fis));
	     ZipEntry entry;
	     while((entry = zis.getNextEntry()) != null) {
	        System.out.println("Extracting: " +entry);
	        int count;
	        byte data[] = new byte[BUFFER_SIZE];
	        
	        //UnArchive the file with the same name as that of the zip file
	        int index = archiveFileName.lastIndexOf(".");
	        String fileName = archiveFileName.substring(0,index) + ".txt";
	        
	        FileOutputStream fos = new FileOutputStream(fileName);
	        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
	        while ((count = zis.read(data, 0, BUFFER_SIZE))!= -1) 
	        {
	           dest.write(data, 0, count);
	        }
	        dest.flush();
	        dest.close();
	     }
	     zis.close();
	     return true;
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			return false;
		}
	}

}
